import { createRouter, createWebHistory } from "vue-router"
import Nav from "@/components/nav.vue"
import { useUserStore } from "@/store/user"
const routerImpl = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      name: "home",
      components: {
        nav: Nav,
        default: () => import("@/pages/home/index.vue")
      }
    },
    {
      path: "/track",
      name: "track",
      components: {
        nav: Nav,
        default: () => import("@/pages/track/index.vue")
      }
    },
    {
      path: "/track/create",
      name: "trackCrate",
      components: {
        nav: Nav,
        default: () => import("@/pages/track/create.vue")
      }
    },
    {
      path: "/identify",
      name: "identify",
      components: {
        nav: Nav,
        default: () => import("@/pages/identify/index.vue")
      }
    },
    {
      path: "/track/edit",
      name: "trackEdit",
      components: {
        nav: Nav,
        default: () => import("@/pages/track/create.vue")
      }
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/pages/login/index.vue")
    },
    {
      path: "/create",
      name: "create",
      component: () => import("@/pages/login/create.vue")
    },
  ]
})


routerImpl.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  if (to.name === "login") {
    return next();
  }
  if (!userStore.user.token) {
    return next({
      name: "login",
      replace: true
    });
  }
  next();
})

export default routerImpl